import time
import numpy as np

st = time.clock()
all_chr = list([35,36,37,38,60,61,62,64,91,92,93,94,95,123,124,125,126])
with open(r'F:\workspace\EulerProject\p059_cipher.txt') as f:
    a = f.readlines()
    b = a[0]
    b = b.replace("\n","")
    bs = b.split(",")
    npa = np.array(bs)
    my_np = npa.astype('int64')
    index_ex = np.arange(len(my_np))
    npaint_0 = my_np[np.where(index_ex % 3 == 0)]
    npaint_1 = my_np[np.where(index_ex % 3 == 1)]
    npaint_2 = my_np[np.where(index_ex % 3 == 2)]

    len0 = len(npaint_0)
    len1 = len(npaint_1)
    len2 = len(npaint_2)

    keys0 = list(range(97,123))
    keys1 = list(range(97,123))
    keys2 = list(range(97,123))

    for i in range(97,123):
        encry_key0 = np.array([i]*len0)
        encry_key1 = np.array([i]*len1)
        encry_key2 = np.array([i]*len2)

        ans0 = np.bitwise_xor(encry_key0, npaint_0)
        ans1 = np.bitwise_xor(encry_key1, npaint_1)
        ans2 = np.bitwise_xor(encry_key2, npaint_2)

        boolean_ans0 = np.isin(ans0,all_chr)
        boolean_ans1 = np.isin(ans1,all_chr)
        boolean_ans2 = np.isin(ans2,all_chr)

        if boolean_ans0.any():
            keys0.remove(i)
        if boolean_ans1.any():
            keys1.remove(i)
        if boolean_ans2.any():
            keys2.remove(i)

    keys = keys0
    keys.extend(keys1)
    keys.extend(keys2)

    keys = keys *(len(my_np) // 3)
    keys.append(keys[0])

    res = np.bitwise_xor(my_np, keys)
    print(np.sum(res))
    print(np.array(keys).tostring().decode("ascii"))
print(time.clock()-st)
